document.addEventListener('DOMContentLoaded', function() {
    const uploadForm = document.getElementById('uploadForm');
    const fileInput = document.getElementById('fileInput');
    const imageResult = document.getElementById('imageResult');
    const videoResult = document.getElementById('videoResult');
    const resultImage = document.getElementById('resultImage');
    const resultVideo = document.getElementById('resultVideo');
    const gestureResult = document.getElementById('gestureResult');
    const errorMessage = document.getElementById('errorMessage');
    const startCameraBtn = document.getElementById('startCamera');
    const cameraFeed = document.getElementById('cameraFeed');
    const liveResult = document.getElementById('liveResult');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    let stream = null;

    // 文件上传处理
    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();

        if (!fileInput.files || fileInput.files.length === 0) {
            showError('请选择文件');
            return;
        }

        const file = fileInput.files[0];
        const formData = new FormData();
        formData.append('file', file);

        hideResults();
        errorMessage.classList.add('hidden');

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showError(data.error);
                return;
            }

            if (data.type === 'image') {
                resultImage.src = `/uploads/${data.filename}`;
                gestureResult.textContent = data.result;
                imageResult.classList.remove('hidden');
            } else if (data.type === 'video') {
                resultVideo.src = `/uploads/${data.filename}`;
                videoResult.classList.remove('hidden');
                resultVideo.load();
            }
        })
        .catch(error => {
            showError('处理文件时出错: ' + error.message);
        });
    });

    // 摄像头处理
    startCameraBtn.addEventListener('click', function() {
        if (stream) {
            stopCamera();
            return;
        }

        navigator.mediaDevices.getUserMedia({ video: true })
            .then(function(s) {
                stream = s;
                cameraFeed.srcObject = stream;
                document.querySelector('.video-container').classList.remove('hidden');
                startCameraBtn.textContent = '关闭摄像头';

                // 设置canvas尺寸与视频相同
                cameraFeed.onloadedmetadata = function() {
                    canvas.width = cameraFeed.videoWidth;
                    canvas.height = cameraFeed.videoHeight;
                };

                // 开始处理视频帧
                processCameraFrame();
            })
            .catch(function(err) {
                showError('无法访问摄像头: ' + err.message);
            });
    });

    function processCameraFrame() {
        if (!stream) return;

        ctx.drawImage(cameraFeed, 0, 0, canvas.width, canvas.height);
        canvas.toBlob(function(blob) {
            const formData = new FormData();
            formData.append('file', blob, 'frame.jpg');

            fetch('/camera', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.result) {
                    liveResult.textContent = data.result;
                }

                // 继续处理下一帧
                requestAnimationFrame(processCameraFrame);
            })
            .catch(error => {
                console.error('Error:', error);
                requestAnimationFrame(processCameraFrame);
            });
        }, 'image/jpeg', 0.8);
    }

    function stopCamera() {
        if (stream) {
            stream.getTracks().forEach(track => track.stop());
            stream = null;
            cameraFeed.srcObject = null;
            document.querySelector('.video-container').classList.add('hidden');
            startCameraBtn.textContent = '开启摄像头';
            liveResult.textContent = '';
        }
    }

    function hideResults() {
        imageResult.classList.add('hidden');
        videoResult.classList.add('hidden');
    }

    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.classList.remove('hidden');
    }

    // 清理摄像头资源当页面关闭
    window.addEventListener('beforeunload', function() {
        stopCamera();
    });
});